/**
 * Created by YF on 2017/8/5.
 */
import regeneratorRuntime from "regenerator-runtime";
function util(opt) {
    const putbaseAPI = opt.uploadApi;//"http://api.huan68.com:9099/%s";
    let value = (data) => {
        if (typeof(data) == "string") {
            console.log("list:" + 'string');
            return data;
        } else if (typeof(data) == "object") {
            return JSON.stringify(data);
        }
    };

    async function post(api, data) {
        let focus = stack.get().onWindowFocusChanged(false);
        // let dialog = stack.get().popup('psychology.user.gerenorder_consultation.sure.xml');
        let response = await fetch(api, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'text/plain',
                'Accept-Charset': 'UTF-8'
            },
            body: value(data)
        });
        // let pck = JSON.parse(response);
        let pck = await response.json();
        console.log("POST.api:" + api);
        console.log("POST.response:" + JSON.stringify(pck));
        console.log("POST.data:" + value(data));
        focus.onWindowFocusChanged(true);
        // dialog.finish();
        if (pck.error) {
            alert(pck.error);
            throw pck.error;
        }
        return pck;
    }

    async function get(api, data) {
        let response = await fetch(sprintf("%s?%s", api, param(data)));
        let pck = JSON.parse(response);
        if (pck.error)
            throw pck.error;
        return pck;
    }

    async function putFile(file) {
        let data = new FormData();
        data.append('image', file);
        let response = await self.fetch("uploadImage", {
            method: 'POST',
            body: data
        });
        let pck = JSON.parse(response);
        console.log("list:" + pck);
        if (pck.error)
            throw pck.error;
        return pck.url;
    }

    async function putFile2(data,type) {
        let response = await fetch2(sprintf(putbaseAPI, sprintf("upload%s",type)), {
            method: 'POST',
            body: data
        });
        let pck = JSON.parse(response);
        if (pck.error)
            throw pck.error;
        return pck;
    };
    return {post,get,putFile2,putFile};
}
export {util};